import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_member/routes/application.dart';
import 'package:flutter_member/stytle/listview_overScrollbehavior.dart';
import 'package:flutter_member/widget/GridViewItem.dart';
import 'package:flutter_member/widget/course_tutorial.dart';
import 'package:flutter_member/widget/loading_dialog.dart';
import 'package:flutter_member/widget/search_width.dart';
import 'package:flutter_member/widget/universal_card.dart';
import 'package:flutter_member/widget/universal_card_item.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:toast/toast.dart';

// 补习的入口文件
class IndexScholar extends StatefulWidget {
  @override
  _IndexScholarState createState() => _IndexScholarState();
}

class _IndexScholarState extends State<IndexScholar> {
  ParseUser user;

  //補習滑動控制器
  var _ieItsController = ScrollController();
  var _ieItsControllerIndex;

  // 搜索中
  bool _searchLoading = false;

  //監聽輸入框焦點
  FocusNode _focusNode = FocusNode();
  List<String> latelyList = ['小一補習', '小二補習', '小三補習'];
  List<String> popularList = ['星期一至六', '全科', '新'];


  /// 搜索结果
  List<dynamic> listSerchResult = [];

  var _search;

  var _searchEditing = new TextEditingController();
  var _focusView = false;
  bool isDrawer = false;
  var _indexedStack = 0;
  var deleteFocus = false;
  var sss;

  /// 补习数据
  List<dynamic> _tuitionServiceList = [];

  ///搜索记录
  List<dynamic> _searchRecordList = [];
  DateTime _lastPressedAt; //上次点击时间
  // tab OR listView
  String type = "tab";
  List<dynamic> listIndexTopData = [
    {
      "title": "出勤紀錄",
      "imagePath": "images/attendance_record.png",
      "path": "/index/subpage/AttendanceRecordPage",
      'color': 0xff93BB24
    },
    {
      "title": "膳食",
      "imagePath": "images/diet.png",
      "path": "/index/subpage/diet",
      'color': 0xff2D7FC7
    },
    {
      "title": "成長紀錄",
      "imagePath": "images/growth_record.png",
      "path": "/index/subpage/growUp",
      'color': 0xff93BB24
    },
    {
      "title": "訂單紀錄",
      "imagePath": "images/index_order.png",
      "path": "/index/subpage/order",
      'color': 0xff2D7FC7
    },
    {
      "title": "學生信息",
      "imagePath": "images/student_message.png",
      "path": "/index/subpage/information",
      'color': 0xff2D7FC7
    },
    {
      "title": "學生相冊",
      "imagePath": "images/album.png",
      "path": "/index/subpage/studentAlbum",
      'color': 0xff93BB24
    },
    {
      "title": "訂閱服務",
      "imagePath": "images/index_service.png",
      "path": "/index/subpage/service",
      'color': 0xff2D7FC7
    },
    {
      "title": "家長列表",
      "imagePath": "images/parents.png",
      "path": "/index/subpage/parents",
      'color': 0xff93BB24
    },
  ];


  void initState() {
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        setState(() {
          _focusView = true;
        });
      } else {
        setState(() {
          _focusView = false;
          //焦點被取消時進行搜索
          if (!deleteFocus) {
            _searchTuition();
          }
        });
      }
    });
    _initUser();
    super.initState();
    _getTuitionServices();
  }

  Future<void> _initUser() async {
    final ParseUser parseUser = await ParseUser.currentUser() as ParseUser;
    setState(() {
      user = parseUser;
    });
  }

  Future<void> _getTuitionServices() async {
    _tuitionServiceList.clear();
    QueryBuilder<ParseObject> queryComment =
    QueryBuilder<ParseObject>(ParseObject('TuitionService'))
      ..includeObject(['category']);
//    只查6條紀錄
    queryComment.setLimit(6);
    var apiResponse = await queryComment.query();

    if (apiResponse.success && apiResponse.results != null) {
      setState(() {
        apiResponse.results.map((f) {
          _tuitionServiceList.add({
            'objectId': f['objectId'],
            'title': f['title'],
            'src': f['category']['cover'] != null
                ? f['category']['cover']['url']
                : null,
            'category': f['category']['title'],
            'blView': false,
            'titleColor': Colors.amberAccent
          });
        }).toList(growable: false);
        _tuitionServiceList[0]['blView'] = false;
      });
    }
  }

  /// 搜索补习
  Future<void> _searchTuition() async {
    setState(() => _searchLoading = true);
    var query = QueryBuilder<ParseObject>(ParseObject("TuitionService"))
      ..whereStartsWith("title", _searchEditing.text)
      ..includeObject(["branches", "category", "package"]);
    var rep = await query.query();
    if (rep.results != null && rep.success) {
      setState(() {
        _searchLoading = false;
        type = "list";
        _searchRecordList.clear();
        _searchRecordList = rep.results.map((e) => e).toList();
        FocusScope.of(context).requestFocus(FocusNode());
      });
    }
    FocusScope.of(context).requestFocus(FocusNode());
    setState(() => _searchLoading = false);
    setState(() => type = "list");
  }

  //下拉刷新
  Future<Null> _refresh() async {
    _initUser();
    return;
  }

  @override
  Widget build(BuildContext context) {
    //獲得屏幕的寬度
    final width = MediaQuery
        .of(context)
        .size
        .width;
    return Scaffold(
        body: GestureDetector(
          onTap: () {
            //點擊任何位置關閉軟鍵盤
            _focusNode.unfocus();
          },
          child: Container(
            child: Column(
              children: <Widget>[
                SearchWidth(
                  src: 'images/ielts_top.png',
                  inputController: _searchEditing,
                  focusNode: _focusNode,
                  hintText: '搜尋補習年級詳情',
                  downColor: Color(0XffDDE7BF),
                  upColor: Color(0Xff9eba31),
                  onChange: (v) => _search = v,
                  onPressed: () => _searchTuition(),
                ),
                Expanded(
                  child: Stack(
                    children: <Widget>[
                      WillPopScope(
                        child: Container(
                            padding: EdgeInsets.only(top: 10),
                            child: EasyRefresh(
                              header: PhoenixHeader(),
                              footer: PhoenixFooter(),
                              onRefresh: () => _getTuitionServices(),
                              child: SingleChildScrollView(
                                child: _body(),
                              ),
                            )),
                        onWillPop: () async {
                          if (type == "list") {
                            setState(() => type = "tab");
                          } else {
                            if (_lastPressedAt == null ||
                                DateTime.now().difference(_lastPressedAt) >
                                    Duration(seconds: 1)) {
                              Toast.show('再按一次退出！', context,
                                  duration: Toast.LENGTH_LONG,
                                  gravity: Toast.CENTER);
                              //两次点击间隔超过1秒则重新计时
                              _lastPressedAt = DateTime.now();
                              return false;
                            }
                            return true;
                          }
                          return null;
                        },
                      ),

                    ],
                  ),
                )
              ],
            ),
          ),
        ));
  }

  /// 主要區域
  Widget _body() {
    if (type == "list") {
      if (_searchLoading == true) {
        return CLoadingDialog(
          text: "搜索中",
        );
      } else if (_searchRecordList.length != 0) {
        return Column(
          children: _searchRecordList
              .map((e) =>
              UniversalCard(title: e["title"], children: [
                UniversalCardItem(icon: "images/1.jpg", title: "null")
              ]))
              .toList(),
        );
      } else {
        return noData();
      }
    } else {
      return Column(
        children: _bodyWidget(),
      );
    }
  }

  /// 主要内容区域
  List<Widget> _bodyWidget() {
    List<Widget> listWidget = [];
    // 如果补习的数据不为空
    listWidget.add(
      Container(
        margin: EdgeInsets.only(top: 15),
        width: MediaQuery
            .of(context)
            .size
            .width,
        height: ScreenUtil().setHeight(136),
        child: _indexTopNavigation(),
      ),
    );
    listWidget.add(_newWidget());
    if (_tuitionServiceList.length != 0) {
      listWidget.add(CourseTutorial(
        listTuitionService: _tuitionServiceList,
        mainTitle: '補習',
        isId: true,
        path: '/signTutoria',
        mainColor: Color(0xff6DC3A3),
        subColor: Color(0xff69BF97),
      ));
    } else {
      print("补习数据空");
    }
    return listWidget;
  }

  /// 广告公告 组件
  Widget _newWidget() {
    //images/Rectangle.png
    return Container(
      width: ScreenUtil().setWidth(340),
      height: ScreenUtil().setHeight(165),
      decoration:
      BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20))),
      child: Image.asset(
        "images/Rectangle.png",
        fit: BoxFit.fill,
      ),
    );
  }


//  無數據
  Widget noData() {
    return Container(
      child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.asset(
                'images/no_result1.png',
              ),
              Container(
                margin: EdgeInsets.only(top: 25),
                child: Image.asset(
                  'images/no_result2.png',
                ),
              )
            ],
          )),
    );
  }

  List<dynamic> list = ["images/Rectangle.png"];

  //刪除搜索紀錄
  void _deleteSearch() {
    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (BuildContext context) {
          return Container(
            padding: EdgeInsets.all(10),
            height: 200,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                    width: MediaQuery
                        .of(context)
                        .size
                        .width - 20,
                    height: 50,
                    decoration: BoxDecoration(
                      color: Color(0Xffececec),
                      borderRadius: BorderRadius.circular(15.0), //邊框
                    ),
                    child: Center(
                      child: Text(
                        '是否要清空搜索紀錄?',
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: Colors.black,
                          fontWeight: FontWeight.bold,
                          fontSize: 20,
                        ),
                      ),
                    )),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      latelyList.clear();
                      Navigator.of(context).pop();
                      //_focusView = false;
                    });
                  },
                  child: Container(
                      margin: EdgeInsets.only(top: 10),
                      width: MediaQuery
                          .of(context)
                          .size
                          .width - 20,
                      height: 50,
                      decoration: BoxDecoration(
                        color: Color(0Xffececec),
                        borderRadius: BorderRadius.circular(15.0), //邊框
                      ),
                      child: Center(
                        child: Text(
                          '確 認',
                          style: TextStyle(
                            color: Color(0Xff4d80c5),
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                          ),
                        ),
                      )),
                ),
                GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Container(
                      margin: EdgeInsets.only(top: 10),
                      width: MediaQuery
                          .of(context)
                          .size
                          .width - 20,
                      height: 50,
                      decoration: BoxDecoration(
                        color: Color(0Xffececec),
                        borderRadius: BorderRadius.circular(15.0), //邊框
                      ),
                      child: Center(
                        child: Text(
                          '取 消',
                          style: TextStyle(
                            color: Colors.red,
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                          ),
                        ),
                      )),
                )
              ],
            ),
          );
        });
  }

  ///  頂部导航栏
  Widget _indexTopNavigation() {
    return GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4, childAspectRatio: 1),
        itemBuilder: (context, index) {
          return GridViewItem(
            title: listIndexTopData[index]['title'],
            imagePath: listIndexTopData[index]['imagePath'],
            color: listIndexTopData[index]['color'],
            onPressed: () =>
                Application.jump(context,
                    user != null ? listIndexTopData[index]['path'] : "/login"),
          );
        },
        itemCount: listIndexTopData.length,
        physics: const NeverScrollableScrollPhysics());
  }
}